from scipy import linalg,array,dot,mat,transpose
from numpy import take
import sys
import random
from context_functions import *
from lattice_functions import *
from os import system

if len(sys.argv)<2: 
	exit()
dbfile = sys.argv[1]
matrix,intent,extent = readContext(dbfile)

minsup = "3%"
universe = len(extent)
each = universe/10
samples = 1

tmatrix = transpose(array(matrix))
files = []

for i in range(0,universe,each):
	for sam in range(samples):
		auxmat = []
		auxext = []
		density = {}
		selind = range(len(extent))
		
		for col in range(len(tmatrix)):
			dens = int(sum(tmatrix[col]))
			if dens not in density:
				density[dens] = []
			density[dens].append(col)
		densorder = density.keys()
		densorder.sort()
		
		delind = []
		#print "densorder",densorder
		#print "density",density
		for k in densorder:
			for l in density[k]:
				#print l,density[k]
				delind.append(l)
		delind = delind[:i]
		#print delind,selind
		for k in delind:
			selind.remove(k)
		#print selind
		auxext = take(extent,selind)
		
		for j in range(len(matrix)):
			auxmat.append(take(matrix[j],selind))
		#print array(auxmat)
		#auxmat.pop(k)
		#extent.pop(k)
		#print "Writing " + dbfile[dbfile.rfind("/")+1:].replace(".rcf","-"+str(i)+".rcf")
		perc = 100-float((100*i)/universe)
		fp = writeContext(dbfile[dbfile.rfind("/")+1:].replace(".rcf","-"+str(perc)+"_"+str(sam)+".rcf"),auxmat,intent,auxext,path="reduced/")
		files.append(fp)
		print fp

for f in files:
	system("./coron.sh " + f + " " + minsup + " " + f[f.rfind("/"):].replace(".rcf",""))

